<template>
  <div class="department-management">
    <el-card>
      <div class="header-actions">
        <h2>部门管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增部门
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入部门名称搜索"
            clearable
            style="width: 300px;"
            @keyup.enter="getDepartmentList"
        >
          <template #append>
            <el-button @click="getDepartmentList" icon="Search" />
          </template>
        </el-input>
      </div>

      <!-- 部门列表 -->
      <el-table
          :data="departmentList"
          border
          style="width: 100%; margin-top: 15px;"
          row-key="id"
          default-expand-all
          v-loading="loading"
      >
        <el-table-column prop="id" label="部门ID" width="80" />
        <el-table-column prop="name" label="部门名称" />
        <el-table-column prop="parentId" label="上级部门" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="createdTime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 部门表单弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑部门' : '新增部门'"
        width="500px"
    >
      <el-form
          :model="formData"
          ref="departmentForm"
          label-width="100px"
          :rules="formRules"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-select
              v-model="formData.parentId"
              placeholder="请选择上级部门"
              clearable
          >
            <el-option
                v-for="dept in allDepartments"
                :key="dept.id"
                :label="dept.displayName"
                :value="dept.id"
                :disabled="formData.id && dept.id === formData.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
              v-model="formData.sort"
              :min="0"
              controls-position="right"
              placeholder="请输入排序号"
          />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
              v-model="formData.description"
              placeholder="请输入部门描述（可选）"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { DepartmentApi } from '@/api/department'

// 部门列表数据
const departmentList = ref([])
const allDepartments = ref([])
const total = ref(0)
const loading = ref(false)
const submitLoading = ref(false)

// 搜索和分页参数
const searchKeyword = ref('')
const queryParams = reactive({
  pageNum: 1,  // 与后端接口参数保持一致
  pageSize: 10,
  name: '',    // 搜索参数改为name，与后端保持一致
  parentId: null
})

// 弹窗相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const departmentForm = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  parentId: null,
  sort: 0,
  description: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '排序号必须为数字', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '部门描述不能超过200个字符', trigger: 'blur' }
  ]
})

// 构建部门树形结构（带层级显示）
const buildDeptTree = (depts, parentId = null, level = 0) => {
  return depts
      .filter(dept => dept.parentId === parentId)
      .map(dept => {
        // 添加层级前缀，直观展示树形结构
        const prefix = level > 0 ? '├' + '─'.repeat(level) + ' ' : ''
        return {
          ...dept,
          displayName: prefix + dept.name,  // 显示带层级的名称
          children: buildDeptTree(depts, dept.id, level + 1)
        }
      })
}

// 获取部门列表
const getDepartmentList = async () => {
  try {
    loading.value = true
    queryParams.name = searchKeyword.value  // 搜索参数映射
    const res = await DepartmentApi.getDepartmentList(queryParams)
    // 适配后端分页数据结构（根据实际返回调整）
    departmentList.value = res.data.records || res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    const errorMsg = error?.response?.data?.msg || '获取部门列表失败'
    ElMessage.error(errorMsg)
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取所有部门（用于下拉选择）
const getAllDepartments = async () => {
  try {
    const res = await DepartmentApi.getDeptTree()
    // 构建树形结构并展平
    const treeData = buildDeptTree(res.data || [])
    const flatten = (tree) => {
      return tree.reduce((acc, node) => {
        acc.push({ ...node })
        if (node.children && node.children.length) {
          acc.push(...flatten(node.children))
        }
        return acc
      }, [])
    }
    allDepartments.value = flatten(treeData)
  } catch (error) {
    console.error('获取所有部门失败:', error)
    ElMessage.error('获取部门结构失败，请刷新页面重试')
  }
}

// 新增部门
const handleAdd = () => {
  isEditMode.value = false
  // 重置表单数据
  Object.assign(formData, {
    id: '',
    name: '',
    parentId: null,
    sort: 0,
    description: ''
  })
  dialogVisible.value = true
  // 重置表单验证状态
  nextTick(() => {
    departmentForm.value?.resetFields()
  })
}

// 编辑部门
const handleEdit = (row) => {
  isEditMode.value = true
  // 填充表单数据
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    parentId: row.parentId,
    sort: row.sort,
    description: row.description || ''
  })
  dialogVisible.value = true
  // 重置表单验证状态
  nextTick(() => {
    departmentForm.value?.clearValidate()
  })
}

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  await departmentForm.value.validate()
  submitLoading.value = true

  try {
    if (isEditMode.value) {
      await DepartmentApi.updateDepartment(formData)
      ElMessage.success('部门更新成功')
    } else {
      await DepartmentApi.createDepartment(formData)
      ElMessage.success('部门创建成功')
    }
    dialogVisible.value = false
    getDepartmentList() // 刷新列表
  } catch (error) {
    const errorMsg = error?.response?.data?.msg || (isEditMode.value ? '部门更新失败' : '部门创建失败')
    ElMessage.error(errorMsg)
    console.error('部门操作失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除部门 "${row.name}" 吗？删除后该部门下的子部门和用户可能会受到影响。`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await DepartmentApi.deleteDepartment(row.id)
      ElMessage.success('部门删除成功')
      getDepartmentList() // 刷新列表
    } catch (error) {
      const errorMsg = error?.response?.data?.msg || '部门删除失败'
      ElMessage.error(errorMsg)
      console.error('部门删除失败:', error)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getDepartmentList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getDepartmentList()
}

// 监听搜索关键词变化，支持防抖
watch(searchKeyword, (newVal) => {
  const timer = setTimeout(() => {
    getDepartmentList()
  }, 500)
  return () => clearTimeout(timer)
})

// 页面挂载时加载数据
onMounted(() => {
  getDepartmentList()
  getAllDepartments()
})

// 引入nextTick
import { nextTick } from 'vue'
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-container {
    flex-direction: column;
    width: 100%;
  }

  .el-input {
    width: 100% !important;
  }
}
</style>